package com.ml.framework.tools;

import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

/**
 * json工具类
 */
public class JsonFormat
{
	private static final ObjectMapper mapper = new ObjectMapper();
	private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	static
	{
		mapper.getSerializationConfig().setDateFormat(formatter);
		mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
	}

	/**
	 * 将对象转成JSON格式字符串返回
	 * 
	 * @param object
	 * @return
	 */
	public static String toJson(Object object)
	{
		StringWriter writer = new StringWriter();
		try
		{
			mapper.writeValue(writer, object);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return writer.toString();
	}

	/**
	 * 将对象转成JSON格式字符串，然后写到琉里
	 * 
	 * @param w
	 * @param object
	 */
	public static void writeJson(Writer write, Object object)
	{
		try
		{
			mapper.writeValue(write, object);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 格式化json数据的格式
	 * 
	 * @return
	 */
	public static String jsomFmt(String json)
	{
		if (json == null)
			return null;

		if (json.charAt(0) == '{')
			json = json.substring(1);
		if (json.charAt(json.length() - 1) == '}')
			json = json.substring(0, json.length() - 1);

		if (json.trim().length() == 0)
			return "{}";
		String[] entitys = json.split(",", json.length() - json.replaceAll(",", "").length() + 1);
		json = "{";
		int len = entitys.length;
		for (int i = 0; i < len; i++)
		{
			String[] items = entitys[i].split(":", 2);
			if(items[0].startsWith("'") && items[0].endsWith("'")) items[0] = items[0].substring(1,items[0].length()-1);
			json += "\"" + items[0] + "\":";
			if (CUtils.isInteger(items[1]) || CUtils.isDecimal(items[1]) || "true".equalsIgnoreCase(items[1]) || "false".equalsIgnoreCase(items[1]))
				json += items[1];
			else{
				if(items[1].startsWith("'") && items[1].endsWith("'")) items[1] = items[1].substring(1,items[1].length()-1);
				json += "\"" + items[1] + "\"";
			}
			if (i < len - 1)
				json += ",";
			else
				json += "}";
		}
		return json;
	}

	/**
	 * 将json字符串转成指定类型的对象
	 * 
	 * @param jsonStr
	 * @param cls
	 * @return
	 */
	public static <T> T readJson(String json, Class<T> cls)
	{
		if (json == null)
			return null;
		try
		{
			return mapper.readValue(json, cls);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

}
